package coder.nav.utils;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpUtils {

    public static String sendPostRequest(String url, Map<String, Object> params) {
        return sendPostRequest(url, params, null);
    }

    public static String sendPostRequest(String url, Map<String, Object> params, Map<String, String> headers) {
        try {
            // 创建 HttpClient 实例
            HttpClient httpClient = HttpClients.createDefault();

            // 创建 HTTP POST 请求
            HttpPost httpPost = new HttpPost(url);

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(30000) // 设置连接超时时间为30秒
                    .setSocketTimeout(30000) // 设置读取超时时间为30秒
                    .build();

            httpPost.setConfig(requestConfig);
            
            // 设置请求头部信息
            httpPost.setHeader("Content-Type", "application/json");
            if(MapUtils.isNotEmpty(headers)) {
                headers.forEach(httpPost::setHeader);
            }

            // 设置请求体内容
            StringEntity requestEntity = new StringEntity(JSONObject.toJSONString(params), "UTF-8");
            requestEntity.setContentType("application/json");
            httpPost.setEntity(requestEntity);

            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);

            // 处理响应
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // 读取响应数据
                String responseString = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
                return responseString;
            } else {
                return "No response from server";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String sendGetRequest(String url, Map<String, String> params) {
        return sendGetRequest(url, params, null);
    }

    public static String sendGetRequest(String url, Map<String, String> params, Map<String, String> headers) {
        try {
            // 创建 HttpClient 实例
            HttpClient httpClient = HttpClients.createDefault();

            // 请求参数
            URIBuilder uriBuilder = new URIBuilder(url);
            if(MapUtils.isNotEmpty(params)) {
                List<NameValuePair> nvps = new ArrayList<>();
                params.forEach((key, value) -> {
                    nvps.add(new BasicNameValuePair(key, value));
                });
                uriBuilder.setParameters(nvps);
            }

            // 创建 HTTP GET 请求
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(30000) // 设置连接超时时间为30秒
                    .setSocketTimeout(30000) // 设置读取超时时间为30秒
                    .build();

            httpGet.setConfig(requestConfig);

            // 设置请求头部信息
            httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
            if(MapUtils.isNotEmpty(headers)) {
                headers.forEach(httpGet::setHeader);
            }

            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpGet);

            // 处理响应
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // 读取响应数据
                String responseString = EntityUtils.toString(entity);
                EntityUtils.consume(entity);
                return responseString;
            } else {
                return "No response from server";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 多线程分页请求
     */
    public static void sendPageRequest(String url, int page, int size, int total, Map<String, String> params) {
        // 最大页数
        int maxPage = (int) Math.ceil(((double) total) / size);
        // 开线程池，最大100
        ExecutorService executor = Executors.newFixedThreadPool(Math.min(maxPage, 100));
        for (; page <= maxPage; page++) {
            int finalPage = page;
            executor.execute(() -> {
                long startTime = System.currentTimeMillis();
                try {
                    Map<String, String> map = new HashMap<>(params);
                    map.put("page", String.valueOf(finalPage));
                    map.put("size", String.valueOf(size));
                    String res = HttpUtils.sendGetRequest(url, map, null);
                    long endTime = System.currentTimeMillis();
                    System.out.println();
                    System.out.println("成功: page = " + finalPage + ", size = " + size);
                    System.out.println("用时: " + (endTime - startTime));
                    System.out.println("结果: " + res);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
        executor.shutdown();
    }

}
